<?php
class MySqlDataBase
{
	protected $db = null;
	protected $connected = false;
    
    public static $FALSE = "0";
    public static $TRUE = "1";

	function connect ($host, $user, $pass, $database)
	{
		$this->db = mysql_connect ($host, $user, $pass);
		if ($this->db!=null) 
		{
			if (mysql_select_db ($database, $this->db)) $this->connected = true;
			$this->usetransactions (false);
		}
	}
	
	function usetransactions ($transactions = false)
	{
		mysql_query ("SET AUTOCOMMIT = ".(($transactions==false)?1:0).";", $this->db);
	}
	
	function transaction_serializable ()
	{
		return mysql_query ("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;", $this->db);
	}
	
	function transaction ()
	{
		return mysql_query ("START TRANSACTION;", $this->db);
	}
	
	function commit ()
	{
		return mysql_query ("COMMIT;", $this->db);
	}
	
	function rollback ()
	{
		return mysql_query ("ROLLBACK;", $this->db);
	}
	
	function close ()
	{
		mysql_close ($this->db);
		$this->db = null;
		$this->connected = false;
	}
	
	function isConnected ()
	{
		return $this->connected;
	}
	
	function error ()
	{
		return mysql_error ($this->db);
	}
	
	function executeQuery ($statement)
	{
		$result = null;
		if ($statement!=null)
		{
			$mysqlresult = mysql_query($statement->getQueryString(), $this->db);
			if ($mysqlresult!=false) $result = new MySqlResult ($mysqlresult);
		}
		return $result;
	}
	
	function executeUpdate ($statement)
	{
		$result = false;
		if ($statement)
		{
			if (mysql_query ($statement->getQueryString(), $this->db) != false) $result = true;
		}
		return $result;
	}
	
	function exists ($table, $name, $value)
	{
		$statement = new DBStatement ("SELECT * FROM ? WHERE ? = ?");
		$statement->setVariable (1, $table);
		$statement->setVariable (2, $name);
		$statement->setString (3, $value);
		return $this->existsStatement ($statement);
	}
	
	function existsStatement ($statement)
	{
		$result = false;
		$mysqlresult = $this->executeQuery ($statement);
		if ($mysqlresult && $mysqlresult->rowsCount()>0)
		{
			$result = true;
			$mysqlresult->free ();
		}
		return $result;
	}
	
	function getID ($table, $name, $value, $id = "id")
	{
		$result = 0;
		$statement = new DBStatement ("SELECT ".$id." FROM ? WHERE ? = ? LIMIT 0,1");
		$statement->setVariable (1, $table);
		$statement->setVariable (2, $name);
		$statement->setString (3, $value);
		$mysqlresult = $this->executeQuery ($statement);
		if ($mysqlresult && $mysqlresult->rowsCount()>0)
		{
			$row = $mysqlresult->getNext();
			$result = $row[$id];
			$mysqlresult->free ();
		}
		return $result;
	}
	
	function getRow ($table, $name, $value)
	{
		$result = null;
		$statement = new DBStatement ("SELECT * FROM ? WHERE ? = ? LIMIT 0,1");
		$statement->setVariable (1, $table);
		$statement->setVariable (2, $name);
		$statement->setString (3, $value);
		$mysqlresult = $this->executeQuery ($statement);
		if ($mysqlresult && $mysqlresult->rowsCount()>0)
		{
			$result = $mysqlresult->getNext();
			$mysqlresult->free ();
		}
		return $result;
	}
	
	function getInsertID ()
	{
		return mysql_insert_id ($this->db);
	}
    
    public function dropTable ($table)
    {
        $statement = new MySqlStatement ("DROP TABLE IF EXISTS ".$table);
        return $this->executeUpdate ($statement);
    }
    
    public function getString ($length, $nullvalue = false, $default = null)
    {
        // de modificat !!!!!!!
        if ($length > 255) $length = 255;
        return "VARCHAR(".$length.")".(($nullvalue==true)?(""):(" NOT NULL")).(($default!=null)?(" DEFAULT ".$default):(""));
    }
    
    public function getNumber ($length=null, $nullvalue = false, $default = null)
    {
        return "INT".(($length!=null)?("(".$length.")"):("")).(($nullvalue==true)?(""):(" NOT NULL")).(($default!=null)?(" DEFAULT ".$default):(""));
    }
    
    public function getDouble ($length=null, $nullvalue = false, $default = null)
    {
        return "FLOAT".(($length!=null)?("(".$length.")"):("")).(($nullvalue==true)?(""):(" NOT NULL")).(($default!=null)?(" DEFAULT ".$default):(""));
    }
    
    public function getBoolean ($nullvalue = false, $default = null)
    {
        return "INT(1)".(($nullvalue==true)?(""):(" NOT NULL")).(($default!=null)?(" DEFAULT ".$default):(""));
    }
    
    public function getDateTime ($nullvalue = false, $default = null)
    {
        return "DATETIME".(($nullvalue==true)?(""):(" NOT NULL")).(($default!=null)?(" DEFAULT ".$default):(""));
    }
    
    public function getDateTimeDMY ($nullvalue = false, $default = null)
    {
        return "DATE".(($nullvalue==true)?(""):(" NOT NULL")).(($default!=null)?(" DEFAULT ".$default):(""));
    }
    
    public function getDateTimeHMS ($nullvalue = false, $default = null)
    {
        return "DATETIME".(($nullvalue==true)?(""):(" NOT NULL")).(($default!=null)?(" DEFAULT ".$default):(""));
    }
    
    public function getDateTimeDMYHMS ($nullvalue = false, $default = null)
    {
        return "DATETIME".(($nullvalue==true)?(""):(" NOT NULL")).(($default!=null)?(" DEFAULT ".$default):(""));
    }
    
    public function getTinyText ($nullvalue = false, $default = null)
    {
        return "TINYTEXT".(($nullvalue==true)?(""):(" NOT NULL")).(($default!=null)?(" DEFAULT ".$default):(""));
    }
    
    public function getText ($nullvalue = false, $default = null)
    {
        return "TEXT".(($nullvalue==true)?(""):(" NOT NULL")).(($default!=null)?(" DEFAULT ".$default):(""));
    }
    
    public function getAutoIncrement ()
    {
        return "INT PRIMARY KEY NOT NULL AUTO_INCREMENT";
    }
    
    public function getEngine ()
    {
        return "ENGINE InnoDB";
    }
}

class MySqlStatement
{
	protected $querystring = "";
	protected $vars;
	
	function MySqlStatement ($query = "")
	{
		$this->querystring = $query;
	}
	
	function setVariable ($pos, $data)
	{
		if (is_int ($pos))
		{
			$this->vars[$pos] = $data;
		}
	}
	
    function setDateTime ($pos, $val)
	{
		if (is_numeric ($pos))
		{
			$this->vars[$pos] = 'FROM_UNIXTIME('.$val.')';
		}
	}
    
    function setDateTimeDMY ($pos, $val)
	{
		if (is_numeric ($pos))
		{
			$this->vars[$pos] = "\"".$val["year"].'-'.$val["month"].'-'.$val["day"]."\"";
		}
	}
    
    function setDateTimeHMS ($pos, $val)
	{
		if (is_numeric ($pos))
		{
			$this->vars[$pos] = "\"".$val["hour"].':'.$val["minutes"].':'.$val["seconds"]."\"";
		}
	}
    
    function setDateTimeDMYHMS ($pos, $val)
	{
		if (is_numeric ($pos))
		{
			$this->vars[$pos] = "\"".$val["year"].'-'.$val["month"].'-'.$val["day"].' '.$val["hour"].':'.$val["minutes"].':'.$val["seconds"]."\"";
		}
	}
    
    function setBoolean ($pos, $val)
	{
		if (is_int ($pos))
		{
			$this->vars[$pos] = ($val == true)?"true":"false";
		}
	}
    
	function setString ($pos, $data)
	{
		if (is_int ($pos) && isset ($data))
		{
            if (get_magic_quotes_gpc() == true) $data = stripslashes($data);
			$this->vars[$pos] = "\"".mysql_real_escape_string ($data)."\"";
		}
	}
	
	function setNumber ($pos, $nr)
	{
		if (is_int ($pos) && is_numeric ($nr))
		{
			$this->vars[$pos] = $nr;
		}
	}
    
    function setDouble ($pos, $nr)
	{
		if (is_int ($pos) && is_numeric ($nr))
		{
			$this->vars[$pos] = $nr;
		}
	}
    
    static function getDateTime ($name)
	{
		return 'UNIX_TIMESTAMP('.$name.') AS '.$name;
	}
    
    static function getDateTimeDMY ($name)
	{
		return "CONCAT(DAYOFMONTH(".$name."),'/',MONTH(".$name."),'/',YEAR(".$name.")) AS ".$name;
	}
    
    static function getDateTimeHMS ($name)
	{
		return "CONCAT(HOUR(".$name."),':',MINUTE(".$name."),':',SECOND(".$name.")) AS ".$name;
	}
    
    static function getDateTimeDMYHMS ($name)
	{
		return "CONCAT(DAYOFMONTH(".$name."),'/',MONTH(".$name."),'/',YEAR(".$name."),' ',HOUR(".$name."),':',MINUTE(".$name."),':',SECOND(".$name.")) AS ".$name;
	}
    
    static function getBoolean ($name)
	{
		return $name;
	}
    
	static function getString ($name)
	{
		return $name;
	}
    
    static function getTinyText ($name)
	{
		return $name;
	}
    
    static function getText ($name)
	{
		return $name;
	}
	
	static function getNumber ($name)
	{
		return $name;
	}
    
    static function getDouble ($name)
	{
		return $name;
	}
	
	function getQueryString ()
	{
		$queryresult = null;
		if ($this->querystring!=null)
		{
			$queryresult = "";
			$pos = 0;
			for ($i=0; $i<strlen ($this->querystring); $i++)
			{
				if ($this->querystring[$i]=='?')
				{
					$pos = $pos + 1;
					if (isset($this->vars[$pos])) $queryresult = $queryresult.$this->vars[$pos];
						else $queryresult = $queryresult."null";
				}
				else $queryresult=$queryresult.$this->querystring[$i];
			}
		}
		return $queryresult;
	}
    
    public static function limitString ($index, $count)
    {
        return "LIMIT ".$index.", ".$count;
    }
}

class MySqlResult
{
	protected $mysqlresult;
	protected $mysqlrows;
	
	function MySqlResult (&$result)
	{
		$this->mysqlresult = $result;
		$this->mysqlrows = mysql_num_rows ($this->mysqlresult);
	}
	
	function rowsCount ()
	{
		return $this->mysqlrows;
	}
	
	function getNext ()
	{
		$row = mysql_fetch_assoc ($this->mysqlresult);
		if ($row == null) $this->free();
		return $row;
	}
	
	function free ()
	{
		mysql_free_result ($this->mysqlresult);
	}
}

/*$db = new DataBase;
$db->connect ("localhost", "root", "", "test");
if ($db->isConnected()) print "yes"; else print "no";
print ($db->error());

$statement = new DBStatement ("DELETE FROM users");
$db->executeUpdate ($statement);

$statement = new DBStatement ("INSERT INTO users SET username = ?, firstname = ?, lastname = ?, idCard = ?");
$statement->setString (1, "unsername1");
$statement->setString (2, "firstname1");
$statement->setString (3, "lastname1");
$statement->setNumber (4, 482374);
$db->executeUpdate ($statement);

$statement = new DBStatement ("SELECT * FROM users");
//$statement->setString (2, "dafdsfsd");
//$statement->setInt (1, 10);
print $statement->getQueryString ();
$res = $db->executeQuery ($statement);
if ($res) while ($row = $res->getNext())
{
	print $row["username"]."<br>";
}*/
?>